namespace CRM_Perf_BenchMark
{
    using System;
    using System.Collections.Generic;
    using Microsoft.VisualStudio.TestTools.WebTesting;
    using System.Net;
    using System.Text;
    using System.Xml;
    
    /// <summary>
    /// 1. Start at Sales homepage
    /// 2. Select Opportunities
    /// 3. Change view to Open Opportunities view
    /// 4. Input a random string and click "Find"
    /// 5. Double click a random Opportunity
    /// 6. Change values inside the open opportunity
    /// 7. Save and close opportunity
    /// </summary>

    public class UpdateOpportunity : CrmWebTest
    {
        public void UpdateOpportunity_PreWebTest(object sender, PreWebTestEventArgs e)
        {
			EntityRequest er = new EntityRequest();
			er.Type = EntityNames.Users;
			er.ReturnAs = EntityNames.Users;
			er.ParentID = EntityManager.Instance.OrgId;

			System.Collections.Hashtable Props = new System.Collections.Hashtable();

            if (e.WebTest.Context.ContainsKey("UserRole"))
            {
                Props.Add("role", e.WebTest.Context["UserRole"]);
            }
            
			EntityRequest OpportunityEr = new EntityRequest();
			OpportunityEr.Type = EntityNames.Opportunities;
			OpportunityEr.ParentID = Guid.NewGuid();
			OpportunityEr.ReturnAs = EntityNames.Opportunities;

			Props.Add(EntityNames.Opportunities, new EntityRequest[] { OpportunityEr });

			er.Props = Props;

			System.Collections.Hashtable Entities = EntityManager.Instance.GetEntities(er);

			user = (CRMEntity)Entities[EntityNames.Users];
			opportunity = (CRMEntity)Entities[EntityNames.Opportunities];
            crmServer = user["CrmServer"];
            tokenKey = EntityManager.Instance.ReadTokenKey(user["organizationid"]);

            orgId = new Guid(user["organizationid"]);

            e.WebTest.UserName = user["domainName"];
            e.WebTest.Password = user["userpassword"];            
        }

        public void UpdateOpportunity_PostWebTest(object sender, PostWebTestEventArgs e)
        {
            EntityManager.Instance.FreeEntity(user);
            EntityManager.Instance.FreeEntity(opportunity);
        }

        public UpdateOpportunity()
        {
            WebRequest.RegisterPrefix("crm", new crmRequestFactory());
            string random = Utils.GetRandomString(2, 2);
            gridXml = GridXmlHelper.OpportunityPageView(-1, openOpportunitiesView, null);
            gridXml2 = GridXmlHelper.OpportunitySearchView(-1, searchOppView, random, null);
            refreshGridXml = GridXmlHelper.OpportunityPageSearchViewRefresh(-1, searchOppView, random, null);

            this.Proxy = null;            
            PreWebTest += new EventHandler<PreWebTestEventArgs>(UpdateOpportunity_PreWebTest);
            PostWebTest += new EventHandler<PostWebTestEventArgs>(UpdateOpportunity_PostWebTest);
        }
        
        public override IEnumerator<WebTestRequest> GetRequestEnumerator()
        {
            AppGridWebService.AppGridWebService ag;
            WebTestRequest wtr;

            this.BeginTransaction("NavOpportunityHomepage");

            // Get the home page
            _root_homepage_aspx hp = new _root_homepage_aspx(user);
            hp.etc = 3;
            yield return (hp);

            this.EndTransaction("NavOpportunityHomepage");

            if (ConfigSettings.Default.alltasks == true)
            {
                this.BeginTransaction("NavOpenOpportunities");

                // Search for the opportunity name   
                ag = new AppGridWebService.AppGridWebService();
                wtr = null;
                try { ag.Reset(gridXml, gridId); }
                catch (crmException x)
                {
                    wtr = (CrmRequest)x.wtr;
                    wtr.Url = Utils.ReplaceServerName(wtr.Url, user);

                    string urlPath = wtr.Url.Remove(0, crmServer.Length);
                    urlPath = urlPath.Remove(0, user["organizationName"].Length + 1);

                    rpcInfo = Utils.GenerateWRPCToken(urlPath, user, tokenKey);

                    headerItem = new WebTestRequestHeader();
                    headerItem.Name = "crmwrpctokentimestamp";
                    headerItem.Value = rpcInfo.timeStamp.ToString();
                    wtr.Headers.Add(headerItem);
                    headerItem = new WebTestRequestHeader();
                    headerItem.Name = "crmwrpctoken";
                    headerItem.Value = rpcInfo.token;
                    wtr.Headers.Add(headerItem);
                    wtr.Method = "Post";
                }
                yield return (wtr);

                this.EndTransaction("NavOpenOpportunities");
            }
            
            this.BeginTransaction("SearchOpportunities");

            ag = new AppGridWebService.AppGridWebService();
            wtr = null;

            try { ag.Reset(gridXml2, gridId); }
            catch (crmException x)
            {
                wtr = (CrmRequest)x.wtr;
                wtr.Url = Utils.ReplaceServerName(wtr.Url, user);

                string urlPath = wtr.Url.Remove(0, crmServer.Length);
                urlPath = urlPath.Remove(0, user["organizationName"].Length + 1);

                rpcInfo = Utils.GenerateWRPCToken(urlPath, user, tokenKey);

                headerItem = new WebTestRequestHeader();
                headerItem.Name = "crmwrpctokentimestamp";
                headerItem.Value = rpcInfo.timeStamp.ToString();
                wtr.Headers.Add(headerItem);
                headerItem = new WebTestRequestHeader();
                headerItem.Name = "crmwrpctoken";
                headerItem.Value = rpcInfo.token;
                wtr.Headers.Add(headerItem);
                wtr.Method = "Post";
            }
            yield return (wtr);

            this.EndTransaction("SearchOpportunities");
            
            this.BeginTransaction("OpenOpportunity");

            // simulate double clicking of lead
            sfa_opps_edit_aspx dp = new sfa_opps_edit_aspx(user);
            dp.id = opportunity["opportunityid"];
            yield return (dp);

            referer = dp.lastResponse.ResponseUri.AbsoluteUri;

            _forms_FormScript_js_aspx f = new _forms_FormScript_js_aspx(user);
            f.etc = 3;
            f.FormType = "main";
            f.FormName = "crmForm";
            headerItem = new WebTestRequestHeader("referer", referer);
            f.Headers.Add(headerItem);
            yield return (f);

            this.EndTransaction("OpenOpportunity");
            
            this.BeginTransaction("UpdateOpportunity");

            // opportunity update form
            dp = new sfa_opps_edit_aspx(user);
            // QueryString Parameters
            dp.id = opportunity["opportunityid"];
            // Form Parameters
            dp.crmFormSubmitXml = EntityXmlHelper.GetUpdateOpportunityXml();

            rpcInfo = Utils.GenerateWRPCToken(sfa_opps_edit_aspx.url, user, tokenKey);
            dp.CRMWRPCToken = rpcInfo.token;
            dp.CRMWRPCTokenTimeStamp = rpcInfo.timeStamp;
            dp.crmFormSubmitMode = 2;
            dp.crmFormSubmitId = new Guid(opportunity["opportunityid"]);
            dp.crmFormUserModified = true;
            dp.crmFormSubmitObjectType = 3;
            dp.crmFormSubmitSecurity = 852023;
            dp.crmFormSubmitOnline = 1;
            yield return (dp);

            // refresh of opportunity list page
 			AppGridWebService.AppGridWebService agws = new AppGridWebService.AppGridWebService();
            WebTestRequest wtrRefresh = null;
            try { agws.Refresh(refreshGridXml); }
            catch (crmException x)
            {
                wtrRefresh = x.wtr;
                wtrRefresh.Url = Utils.ReplaceServerName(wtrRefresh.Url, user);

                string urlPath = wtrRefresh.Url.Remove(0, crmServer.Length);
                urlPath = urlPath.Remove(0, user["organizationName"].Length + 1);

                rpcInfo = Utils.GenerateWRPCToken(urlPath, user, tokenKey);

                headerItem = new WebTestRequestHeader();
                headerItem.Name = "crmwrpctokentimestamp";
                headerItem.Value = rpcInfo.timeStamp.ToString();
                wtrRefresh.Headers.Add(headerItem);
                headerItem = new WebTestRequestHeader();
                headerItem.Name = "crmwrpctoken";
                headerItem.Value = rpcInfo.token;
                wtrRefresh.Headers.Add(headerItem);
                wtrRefresh.Method = "Post";
            }
            yield return (wtrRefresh);

            this.EndTransaction("UpdateOpportunity");
        }

        private string gridXml;
        private string gridXml2;
        private string refreshGridXml;
        private static string gridId = "crmGrid";

        private CRMEntity user;
        private CRMEntity opportunity;
        private string crmServer;
        private string tokenKey;

        private static string searchOppView = "3F6D889E-6549-4025-9CE0-4C4103EFB6A3";
        private static string openOpportunitiesView = "00000000-0000-0000-00AA-000010003001";

        private Guid orgId;
        private WRPCInfo rpcInfo;
        private WebTestRequestHeader headerItem;
        private string referer;
    }
}